import React, { useState, useEffect, useCallback } from 'react'
import { DatePicker, Button, Form, Select } from 'antd'
import { QuestionCircleOutlined } from '@ant-design/icons'
import { FilterContainer } from '@/appComponents/Filter'
import {
  PlusOutlined,
  SearchOutlined,
  DownloadOutlined,
  UploadOutlined
} from '@ant-design/icons'
import { getPlanHistoryList, getAdmList } from '&/api/electricity'
import dayjs from 'dayjs'

const Filter = ({
  onQuery,
  paramsData,
  setParamsData,
  timeList,
  setHistoryId,
  btnStatus,
  setBtnStatus,
  submitHistoryTable,
  onDownloadExcel,
  upDateDataSource,
  setOpenTime
}) => {
  const [countValues, setCountValues] = useState([])
  const [isDisabled, setIsDisabled] = useState(false)
  const [isMeasure, setIsMeasure] = useState(1)
  const [isManual, setIsManual] = useState(1)
  const [timeRange, setTimeRange] = useState({
    start_time: null,
    end_time: null
  })
  const [time, setTime] = useState({
    start_time: paramsData.start_time,
    end_time: paramsData.end_time
  })
  const MeasureList = [
    {
      name: '全部',
      value: 1
    },
    {
      name: '是',
      value: 2
    },
    {
      name: '否',
      value: 3
    }
  ]
  const pgonQueryChange = (value, key) => {
    // 使用format方法将moment对象格式化为字符串
    const start_time = value[0].format('YYYY-MM-DD HH:00:00')
    const end_time = value[1].format('YYYY-MM-DD HH:00:00')
    // 如果需要进一步处理，比如发送到后端或更新其他状态，也可以在这里进行
    localStorage.setItem('pgData', JSON.stringify([{ start_time, end_time }]))
  }
  const onQueryChange = (v, t) => {
    if (t == 'time') {
      const st = v[0].format('YYYY-MM-DD HH:00:00')
      const et = v[1].format('YYYY-MM-DD HH:00:00')
      setParamsData((state) => {
        state.start_time = st
        state.end_time = et
        return {
          ...state
        }
      })
    }
    if (t == 'area') {
      setParamsData((state) => {
        state.county_id = v
        return {
          ...state
        }
      })
    }
  }
  const click = () => {
    let newParamsData = {}
    for (let key in paramsData) {
      if (paramsData[key] != (-1 || '-1')) {
        newParamsData[key] = paramsData[key]
      }
    }
    onQuery && onQuery(newParamsData)
  }
  const handleMeasureChange = (v) => {
    setIsMeasure(v)
    upDateDataSource(v)
  }

  useEffect(() => {
    getAdmListRequest()
  }, [])
  // 区的接口
  const getAdmListRequest = async () => {
    const res = await getAdmList({ adm_level: '3' })
    res.unshift({ county_id: -1, county_name: '全部' })
    setCountValues(res)
  }
  localStorage.setItem('paramsData', JSON.stringify(time))
  useEffect(() => {
    console.log(new Date())
    const userData = localStorage.getItem('user')

    if (userData) {
      const userObject = JSON.parse(userData)
      console.log(userObject.role_level, 'aaa')

      // 假设我们根据 role_level 的值决定是否禁用日期选择器
      // 比如当 role_level 小于某个特定值时禁用它
      console.log(userObject.userid)
      setIsDisabled(userObject.userid != '694cc8d3-3acb-4db3-9800-888888888888')
    }
  }, [])

  useEffect(() => {
    const currentTime = new Date()
    console.log(paramsData, 'asdsad')
    currentTime.setHours(currentTime.getHours() - 7)
    getPlanHistoryList({
      plan_id: 61
    }).then((data) => {
      setTime({
        start_time: data[data.length - 1].start_time,
        end_time: data[data.length - 1].end_time
      })
    })
  }, [paramsData])

  return (
    <FilterContainer>
      <div
        style={{
          width: '100%',
          display: 'flex',
          justifyContent: 'space-between'
        }}
      >
        <div>
          <Form layout="inline">
            <Form.Item label="评估创建：">
              <DatePicker.RangePicker
                disabled={isDisabled}
                showTime={'YYYY-MM-DD HH:00:00'}
                showNow
                format={'YYYY-MM-DD HH:00:00'}
                onChange={(v) => {
                  pgonQueryChange(v, 'time')
                }}
              />
            </Form.Item>
            <Form.Item style={{ width: 130 }}>
              <Button
                disabled={isDisabled}
                type="primary"
                onClick={() => {
                  submitHistoryTable('1')
                }}
                icon={<PlusOutlined />}
              >
                创建
              </Button>
            </Form.Item>
            <Form.Item label="当前评估时间：">
              <QuestionCircleOutlined
                style={{ cursor: 'pointer', marginRight: 5 }}
                onClick={() => {
                  setOpenTime(true)
                }}
              />
              <DatePicker.RangePicker
                disabled
                showTime={'YYYY-MM-DD HH:00:00'}
                showNow
                value={[dayjs(time.start_time), dayjs(time.end_time)]}
                format={'YYYY-MM-DD HH:00:00'}
                onChange={(v) => {
                  onQueryChange(v, 'time')
                }}
              />
            </Form.Item>
            <Form.Item label="区域选择">
              <Select
                placeholder={`请选择`}
                value={paramsData?.county_id}
                onChange={(v) => onQueryChange(v, 'area')}
              >
                {countValues &&
                  countValues.map((item, key) => {
                    return (
                      <Select.Option key={key} value={item.county_id}>
                        {item.county_name}
                      </Select.Option>
                    )
                  })}
              </Select>
            </Form.Item>
            <Form.Item label="是否落实措施(自动)">
              <Select
                placeholder={`请选择`}
                value={isMeasure}
                onChange={(v) => handleMeasureChange(v)}
              >
                {MeasureList.map((item, key) => {
                  return (
                    <Select.Option key={key} value={item.value}>
                      {item.name}
                    </Select.Option>
                  )
                })}
              </Select>
            </Form.Item>
          </Form>
        </div>
        <div>
          <Form layout="inline">
            <Form.Item style={{ width: 130 }}>
              <Button
                type="primary"
                onClick={() => click('query')}
                icon={<SearchOutlined />}
              >
                查询
              </Button>
            </Form.Item>
            <Form.Item>
              <Button
                onClick={() => {
                  submitHistoryTable()
                }}
                icon={<UploadOutlined />}
                type="primary"
              >
                提交
              </Button>
            </Form.Item>
            <Form.Item>
              <Button
                icon={<DownloadOutlined />}
                type="primary"
                style={{ marginRight: '10px' }}
                onClick={() => {
                  onDownloadExcel()
                }}
              >
                导出
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </FilterContainer>
  )
}

export default Filter
